<template>
	<view class="u-page">
		<view class="u-demo-block">
			<view class="u-demo-block__content">
				<view class="u-page__button-item">
					<u-button text="添加分组" size="small" type="primary" icon="plus" @click="AddGroup"></u-button>
				</view>
				<view class="u-page__button-item">
					<u-button text="添加设备" size="small" type="primary" icon="plus" @click="Add"></u-button>
				</view>
				<view class="u-page__button-item">
					<u-button text="扫码添加设备" size="small" type="primary" icon="plus"></u-button>
				</view>
				<view class="right">
					<u-icon name="search" color="#000" size="30" class="search"></u-icon>
				</view>
			</view>
		</view>
		<view style="margin-top: -50px;width: 620rpx;margin-left: 30rpx;">
			<u-button text="切换至分组" type="primary" icon="minus" shape="circle" color="#ccc"></u-button>
		</view>
		<view style="margin-top: 20px;">
			<u-tabs :list="list4" :activeStyle="{
			width:'50px',
			height:'40px',
			'line-height':'40px',
			'text-align':'center',
			'font-size':'14px',
			background:'#1989F8',
			color: '#fff',
			transform: 'scale(1.05)'
		}" :inactiveStyle="{
			width:'50px',
			height:'40px',
			'line-height':'40px',
			'text-align':'center',
			'font-size':'14px',
			background:'#F2F2F2',
			color: '#606266',
			transform: 'scale(1)'
		}" itemStyle="padding-left: 15px; padding-right: 15px; height: 34px;" :current="current" @click="selectTab">
			</u-tabs>
		</view>



		<view class="block" v-for="(item, index) in deviceList" :key="index">
			<u-collapse>
				<u-collapse-item :title="item.alarmsName" icon="setting">
					<view style="width: 100%;margin-top: 10rpx;">
						<u-button text="编辑" type="primary" size="small" @click="edit(item)"></u-button>
					</view>
					<view style="width: 100%;margin-top: 10rpx;">
						<u-button text="曲线分析" type="primary" size="small" @click="order(item)"></u-button>
					</view>
					<view style="width: 100%;margin-top: 10rpx;">
						<u-button text="地图" type="primary" size="small" @click="getLocationMap(item)"></u-button>
					</view>
					<view style="width: 100%;margin-top: 10rpx;">
						<u-button text="删除" type="error" size="small" @click="delDevice(item)"></u-button>
					</view>
				</u-collapse-item>
			</u-collapse>
			<view class="block-bottom">
				<view class="first">
					<view class="device">设备编号:{{item.equipmentNo}}</view>
					<view class="status">状态:{{item.onlineStatus}}</view>
				</view>
				<view class="two">
					<view>分组名称:{{item.alarmsGroup}}</view>
				</view>
				<view class="bottom">
					<view class="see">
						<u-button type="primary" size="small" text="控制" @click="control(item)"></u-button>
					</view>
				</view>
			</view>
		</view>


		<u-popup :safeAreaInsetBottom="true" :safeAreaInsetTop="true" :mode="popupData.mode" :show="showAdd"
			:round="popupData.round" :overlay="popupData.overlay" :borderRadius="popupData.borderRadius"
			:closeable="popupData.closeable" :closeOnClickOverlay="popupData.closeOnClickOverlay" @close="close"
			@open="open">
			<view class="u-popup-slot" :style="{
					width: '600rpx',
					height:'800rpx',
				}">
				<view class="title">{{title}}</view>
				<u-line></u-line>
				<view class="form">
					<u--form labelPosition="left" :model="model1">
						<u-form-item label="名称" borderBottom ref="item1" required labelWidth="100">
							<u--input v-model="model1.alarmsName" border="none" placeholder="名称"></u--input>
						</u-form-item>
						<u-form-item label="设备编号" borderBottom ref="item1" required labelWidth="100">
							<u--input v-model="model1.equipmentNo" border="none" placeholder="设备编号"></u--input>
						</u-form-item>
						<u-form-item label="初始密码" borderBottom ref="item1" required labelWidth="100">
							<u--input v-model="model1.password" border="none" placeholder="初始密码"></u--input>
						</u-form-item>
						<u-form-item label="设备分组" borderBottom @click="showGroup2 = true; hideKeyboard()" ref="item1"
							labelWidth="100">
							<u--input v-model="model1.alarmsGroup" disabled disabledColor="#ffffff" placeholder="请选择分组"
								border="none"></u--input>
							<u-icon slot="right" name="arrow-right"></u-icon>
						</u-form-item>
						<u-form-item label="设备类型" borderBottom @click="showDeviceType = true; hideKeyboard()"
							ref="item1" labelWidth="100">
							<u--input v-model="model1.alarmsType" disabled disabledColor="#ffffff" placeholder="请选择设备类型"
								border="none"></u--input>
							<u-icon slot="right" name="arrow-right"></u-icon>
						</u-form-item>
						<u-form-item label="设备地址" borderBottom ref="item1" required labelWidth="100" @click="selectMapAddress">
							<u--input v-model="model1.address" border="none" placeholder="设备地址" ></u--input>
						</u-form-item>
					</u--form>
				</view>
				<view class="bottom">
					<view style="width: 50%;">
						<u-button text="取消" @click="AddCancel"></u-button>
					</view>
					<view style="width: 50%;">
						<u-button :custom-style="buttonStyle" @click="AddDevice">保存</u-button>
					</view>
				</view>
			</view>
		</u-popup>
		<u-popup :safeAreaInsetBottom="true" :safeAreaInsetTop="true" :mode="popupData.mode" :show="showGroup"
			:round="popupData.round" :overlay="popupData.overlay" :borderRadius="popupData.borderRadius"
			:closeable="popupData.closeable" :closeOnClickOverlay="popupData.closeOnClickOverlay" @close="close"
			@open="open">
			<view class="u-popup-slot" :style="{
					width: '600rpx',
					height:'320rpx',
				}">
				<view class="title">添加分组</view>
				<u-line></u-line>
				<view class="form">
					<u--form labelPosition="left" :model="groupModel" :rules="groupRule" ref="form1">
						<u-form-item label="分组名称" borderBottom required labelWidth="100" prop="name" ref="item1">
							<u--input v-model="groupModel.name" border="none" placeholder="分组名称"></u--input>
						</u-form-item>
					</u--form>
				</view>
				<view class="bottom">
					<view style="width: 50%;">
						<u-button text="取消" @click="GroupCancel"></u-button>
					</view>
					<view style="width: 50%;">
						<u-button :custom-style="buttonStyle" @click="CreateGroup">保存</u-button>
					</view>
				</view>
			</view>
		</u-popup>

		<u-action-sheet :show="showGroup2" :actions="groupList" title="请选择分组" @close="showGroup2 = false"
			@select="groupSelect">
		</u-action-sheet>
		<u-action-sheet :show="showDeviceType" :actions="deviceTypeList" title="请选择设备类型" @close="showDeviceType = false"
			@select="deviceTypeSelect">
		</u-action-sheet>
		<u-modal content="确定删除该设备吗" :show="showDelete" showCancelButton closeOnClickOverlay @confirm="confirmDel"
			@cancel="cancelDel" @close="closeDel"></u-modal>
	</view>
</template>

<script>
	import {
		CreateGroup,
		GroupList,
		CreateDevice,
		listToMiniApp,
		updateDevice,
		delDevice
	} from '../../../api/index.js'
	export default {
		data() {
			return {
				current: 0,
				//添加设备分组
				showGroup: false,
				groupModel: {
					name: ''
				},
				groupRule: {
					'name': [{
						type: 'string',
						required: true,
						message: '请填写姓名',
						trigger: ['blur', 'change']
					}],
				},

				//添加设备模块
				showAdd: false,
				showGroup2: false,
				groupList: [],
				showDeviceType: false,
				deviceTypeList: [{
						name: '光伏',
					},
					{
						name: '摄像头',
					}
				],
				model1: {
					"id": 0,
					"alarmsName": "",
					"equipmentNo": "",
					"password": "",
					"alarmsGroup": "",
					"address": "",
					"alarmsType": "",
          "latitude": "",
          "longitude": "",
				},

				popupData: {
					round: 10,
					overlay: true,
					mode: 'center',
					borderRadius: '',
					closeable: false,
					closeOnClickOverlay: true
				},
				buttonStyle: {
					// 注意驼峰命名，并且值必须用引号包括，因为这是对象
					color: '#3C9CFF'
				},
				list4: [{
					name: '全部'
				}, {
					name: '正常'
				}, {
					name: '离线',
				}, {
					name: '故障'
				}, {
					name: '报警'
				}, {
					name: '开灯'
				}, {
					name: '关灯'
				}],
				deviceList: [],
				id: 0,
				onlineStatus: '',
				title: '编辑设备',

				showDelete: false,
				deviceId: 0,
			}
		},
		created() {
			//#ifdef MP-WEIXIN
			wx.showShareMenu({
				withShareTicket: true,
				menus: ['shareAppMessage', 'shareTimeline']
			});
			//#endif
		},
		onLoad(options) {
			console.log('options', options);
			this.id = options.id
			let name=options.name
			this.getGroupList()
			wx.setNavigationBarTitle({
				title: name
			});
			this.getDeviceList(options.id)
		},
		onReady() {
			//如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
			this.$refs.form1.setRules(this.groupRule)
		},
		methods: {
			delDevice(item) {
				this.deviceId = item.id
				this.showDelete = true
			},
			confirmDel() {
				this.showDelete = false
				delDevice(this.deviceId).then(res => {
					uni.$u.toast('删除成功')
					this.getDeviceList()
				})
			},
			cancelDel() {
				this.showDelete = false
			},
			closeDel() {
				this.showDelete = false
			},
			edit(obj) {
				console.log(obj)
				this.model1.id = obj.id
				this.model1.alarmsName = obj.alarmsName
				this.model1.equipmentNo = obj.equipmentNo
				this.model1.password = obj.password
				this.model1.address = obj.address
				this.model1.alarmsType = obj.alarmsType
				this.model1.alarmsGroup = obj.alarmsGroup
				this.title = '编辑设备';
        this.showAdd = true
			},
			async getLocationMap(item) {
				console.log('item', item);
				uni.openLocation({
					latitude: parseFloat(item.latitude),
					longitude: parseFloat(item.longitude),
					success: function() {
						console.log('success');
					}
				});
			},
			order(item){
				console.log(item)
				uni.navigateTo({
					url:'/pageIndex/pages/index/baobiao/baobiao?equipmentNo='+item.equipmentNo
				})
			},
			selectTab(e) {
				console.log(e)
				this.current = e.index
				let onlineStatus = this.list4[e.index].name
				this.onlineStatus = onlineStatus
				this.getDeviceList()
			},
			getDeviceList() {
				const _this = this
				if (this.onlineStatus != '全部') {
					var param = {
						pageNum: 1,
						pageSize: 999,
						groupId: this.id,
						onlineStatus: this.onlineStatus
					}
					listToMiniApp(param).then(res => {
						console.log(res)
						this.deviceList = res.data[0].iotAlarmsList
					})
				} else {
					var param = {
						pageNum: 1,
						pageSize: 999,
						groupId: this.id
					}
					listToMiniApp(param).then(res => {
						console.log(res)
						this.deviceList = res.data[0].iotAlarmsList
					})
				}
			},
			getGroupList() {
				const _this = this
				var param = {
					pageNum: 1,
					pageSize: 999
				}
				listToMiniApp(param).then(res => {
					console.log(res.data)
					for (var index in res.data) {
						let obj = {
							name: res.data[index].name
						}
						_this.groupList.push(obj)
						console.log(_this.groupList)
					}
				})
			},
			control(item) {
				// uni.navigateTo({
				// 	url: '/pageIndex/pages/index/control2?id=' + id
				// })
				uni.navigateTo({
					url: '../../../pages/index/controlHome?id=' + item.id+'&equipmentNo='+item.equipmentNo+'&latitude='+item.latitude
					+'&longitude='+item.longitude
				})
			},
			CreateGroup() {
				const _this = this
				// 如果有错误，会在catch中返回报错信息数组，校验通过则在then中返回true
				_this.$refs.form1.validate().then(res => {
					CreateGroup(_this.groupModel).then(res => {
						_this.showGroup = false
						uni.$u.toast('保存成功')
					})
				}).catch(errors => {
					console.log(errors)
					uni.$u.toast('校验失败')
				})
			},
			AddDevice() {
				const _this = this
				if (_this.model1.id > 0) {
					updateDevice(_this.model1).then(res => {
						_this.showAdd = false
						_this.getDeviceList()
						uni.$u.toast('保存成功')
					})
				} else {
					CreateDevice(_this.model1).then(res => {
						_this.showAdd = false
						_this.getDeviceList()
						uni.$u.toast('保存成功')
					})
				}
			},
			AddGroup() {
				this.showGroup = true
			},
			click(e) {
				this.
				console.log('click', e);
			},
			Add() {
				this.title = "添加设备"
				this.showAdd = true
			},
      selectMapAddress() {
        console.log('12312122312')
        uni.chooseLocation({
          success:  (res) => {
            const info = JSON.parse(JSON.stringify(res))
            console.log('位置名称：' + res.name);
            console.log('详细地址：' + res.address);
            console.log('纬度：' + res.latitude);
            console.log('经度：' + res.longitude);
            console.log('info', info)
            // setTimeout(() => {
              this.model1.address = info.address
              this.model1.latitude = info.latitude
              this.model1.longitude = info.longitude
            // }, 100);

          }
        });
      },
			open() {
				// console.log('open');
			},
			close() {
				this.show = false
				// console.log('close');
			},
			AddCancel() {
				this.showAdd = false
			},
			GroupCancel() {
				this.showGroup = false
			},
			hideKeyboard() {
				uni.hideKeyboard()
			},
			groupSelect(e) {
				this.model1.alarmsGroup = e.name
			},
			deviceTypeSelect(e) {
				this.model1.alarmsType = e.name
			},
		}
	}
</script>

<style lang="scss">
	.u-popup-slot {
		position: relative;

		.title {
			width: 100%;
			height: 30rpx;
			display: flex;
			flex-direction: row;
			align-items: center;
			justify-content: center;
			margin-bottom: 20rpx;
		}

		.bottom {
			width: 100%;
			position: absolute;
			bottom: 0;
			display: flex;
			flex-direction: row;
		}

		.form {
			margin: 20px;
		}
	}

	.u-page {
		&__button-item {
			margin: 0 10rpx 15px 0;
		}
	}

	.u-demo-block__content {
		flex-direction: row;
		flex-wrap: nowrap;
		align-items: center;
	}

	.u-demo-block {
		display: flex;
		align-items: center;
	}

	.u-page__button-item {
		width: 100px;
		height: 60px;
	}

	.search {
		margin-top: -10px;
	}

	.right {
		margin-top: -88rpx;
	}

	.block {
		margin-top: 20px;
		border: 1px solid #ccc;
		border-radius: 5px;
		padding: 5px;

		.block-top {
			display: flex;
			flex-direction: row;
			align-items: center;
			justify-content: space-between;
			flex: 1;

			.left {
				flex-grow: 1;
				display: flex;
				flex-direction: row;
				height: 40px;
			}

			.middle {
				margin-left: 10px;
				font-size: 20px;
				height: 40px;
				line-height: 40px;
			}

			.right {
				flex-grow: 1;
				margin-right: 100px;
			}
		}

		.block-bottom {
			font-size: 14px;
			margin-top: 10px;
			padding-left: 30rpx;
			padding-bottom: 30rpx;

			.first {
				display: flex;
				flex-direction: row;
				justify-content: space-between;
				margin-right: 10px;
				margin-bottom: 10px;

				.device {
					flex-grow: 1;
				}
			}

			.two {}

			.bottom {
				display: flex;
				flex-direction: row;
				justify-content: flex-end;
				margin-right: 20px;

				.see {
					width: 50px;
				}
			}
		}
	}
</style>